package com.java.IO.print_stream;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class PrintWriterAPI {
    public static void main(String[] args) throws IOException {
        String path = "File和IO流\\com\\java\\files\\char_stream.txt";
        
        // 创建对象：若父级路径不存在则抛出异常FileNotFoundException，若文件不存在则会创建，若文件已存在则清空文件内数据。布尔类型的参数表示是否开启自动刷新，字符打印流有缓冲区所以不会自动刷新
        PrintWriter printWriter1 = new PrintWriter(path);
        PrintWriter printWriter2 = new PrintWriter(new File(path));
        PrintWriter printWriter3 = new PrintWriter(path, "UTF-8");
        PrintWriter printWriter4 = new PrintWriter(new FileWriter(path));
        PrintWriter printWriter5 = new PrintWriter(new FileWriter(path), true);
        
        // write：写出数据到本地文件，若参数为整数则会转为ASCII对应的字符
        printWriter1.write(97); // a
        printWriter1.write('9'); // 9
        printWriter1.write('中'); // 中
        printWriter1.write('中'); // 中
        printWriter1.write("\r\n"); // 换行(Windows\r\n、Linux\n、Mac\r)
        printWriter1.write(new char[]{'a', '哈', 'c', 'd'}); // a哈cd
        printWriter1.write(new char[]{'a', '哈', 'c', 'd', 101, 102, 103}, 3, 2); // de
        printWriter1.write("啊啊啊Hello"); // 啊啊啊Hello
        printWriter1.write("啊啊啊Hello", 3, 2); // He
        
        // print：写出任意数据到本地文件，不换行，数据原样写出
        printWriter1.print(97); // 97
        printWriter1.print("9"); // 9
        printWriter1.print("中"); // 中
        
        // printf：写出带占位符的数据到本地文件，不换行，数据原样写出
        printWriter1.printf("%S%s", "中", "文"); // 中文
        
        // println：写出任意数据到本地文件，换行，数据原样写出
        printWriter1.println(97); // 97\r\n
        printWriter1.println("9"); // 9\r\n
        printWriter1.println("中"); // 中\r\n
        
        // flush：缓冲区数据写出到目标地并清空缓冲区。打断点到此并观察断点执行前后目标地数据
        printWriter1.flush();
        
        // close：关闭流并释放资源，若此前未执行flush则充当部分flush作用将缓冲区数据写出到目标地
        printWriter1.close();
    }
}
